//index.js
//获取应用实例
const app = getApp()
//加载腾讯位置服务js文件（必须）
var qqmap = require('../../utils/qqmap-wx-jssdk.js')
Page({
  data: {
    discount: [], //优惠券
    // 用户选择的优惠券id
    showModel: false,
    address: {},
    // 组件所需的参数
    nvabarData: {
      showCapsule: 0, //是否显示左上角图标   1表示显示    0表示不显示
      title: '首页', //导航栏 中间的标题
    },
    retu: false,
    imgUrls: [],
    ids: [],
    lo: 'https://xiaochengxu.printeasy.top',
    // 此页面 页面内容距最顶部的距离
    height: app.globalData.height * 2 + 20,
    //城市
    city: '北京市',
    jqm: '',
    indicatorDots: true, // 是否显示面板指示点
    autoplay: true, // 是否自动切换
    interval: 5000, // 自动切换时间间隔
    duration: 500, // 滑动动画时长
    circular: true, // 是否采用衔接滑动
    /*自定义轮播图 配置*/
    slider: [{
      id: '0',
      linkUrl: 'pages/index/index',
      picUrl: 'http://img1.gtimg.com/rushidao/pics/hv1/20/108/1744/113431160.jpg'
    },
    {
      id: '1',
      linkUrl: 'pages/index/index',
      picUrl: 'http://g.hiphotos.baidu.com/zhidao/pic/item/ac4bd11373f08202b4a9a53a4bfbfbedab641bff.jpg'
    },
    {
      id: '2',
      linkUrl: 'pages/index/index',
      picUrl: 'http://file02.16sucai.com/d/file/2014/0829/b871e1addf5f8e96f3b390ece2b2da0d.jpg'
    }
    ]
  },

  godrawings_printing: function () {
    const pageUrl = '/modelA/pages/drawings_printing/drawings_printing';
    if (this.redirectLogin() && this.addOrUpdatePrinter(pageUrl)) {
      //跳转
      wx.navigateTo({
        url: pageUrl
      })
    }
  },
  ScanningCopying: function () {
    const pageUrl = '/printer/index/index';
    if (this.redirectLogin() && this.addOrUpdatePrinter(pageUrl)) {
      //跳转
      wx.navigateTo({
        url: pageUrl
      })
    }
  },
  addOrUpdatePrinter: function (url) {
    // TODO 添加打印机
    if (app.globalData.jqm.indexOf("@") >= 0) return true;
   console.log('?');
    wx.showModal({
      title: '请添加打印机',
      success(res) {
        if (res.confirm) {
          wx.scanCode({
            success(res) {
              console.log(res.result);
              let bm = res.result
              if (!(/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/.test(bm))) {
                wx.showModal({
                  title: '设备添加失败',
                })
              } else {
                app.globalData.jqm = res.result
                wx.showModal({
                  title: '设备添加成功',
                  icon: 'none',
                  success() {
                    wx.navigateTo({
                      url: url,
                    })
                  }
                })
              }
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
    return false;
  },
  redirectLogin: function () {
    if (app.globalData.token) return true;
    wx.reLaunch({
      url: '/pages/login/login',
    })
    // wx.showModal({
    //   title: '请登录',
    //   icon: 'none',
    //   success: function () {

    //   }
    // })
    return false;
  },
  godocuments_printing: function () {
    const pageUrl = '/modelA/pages/documents_printing/documents_printing';
    if (this.redirectLogin() && this.addOrUpdatePrinter(pageUrl)) {
      //跳转
      wx.navigateTo({
        url: pageUrl
      })
    }
  },
  goequipment_repair: function () {

    const pageUrl = '/modelA/pages/equipment_repair/equipment_repair';
    if (this.redirectLogin()) {
      //跳转
      wx.navigateTo({
        url: pageUrl
      })
    }
  },
  goequipment_rental: function () {
    const pageUrl = '/modelA/pages/equipment_rental/equipment_rental';
    if (this.redirectLogin()) {
      //跳转
      wx.navigateTo({
        url: pageUrl
      })
    }
  },
  goequipment_procurement: function () {
    const pageUrl = '/modelA/pages/equipment_procurement/equipment_procurement';
    if (this.redirectLogin()) {
      //跳转
      wx.navigateTo({
        url: pageUrl
      })
    }
  },
  gooffice_supplies: function () {
    const pageUrl = '/modelA/pages/office_supplies/office_supplies';
    if (this.redirectLogin()) {
      //跳转
      wx.navigateTo({
        url: pageUrl
      })
    }
  },

  islogin() {
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) { } else {
          // 未授权，跳转到授权页面

        }
      }
    })
  },
  onShareAppMessage: function () { },
  loadCoupon: function () {
    const that = this;
    // 查询可领优惠券
    let url = app.globalData.URL + 'goods/coupon/usable/list';
    let data = {};
    app.wxRequest('GET', url, data, (res) => {
      if (res.code == 200 && res.rows != '') {
        let ids = [];
        let i = 0;
        for (i in res.rows) {
          ids.push(res.rows[i].id)
          console.log(ids)
        }
        that.setData({
          showModal: true,
          discount: res.rows,
          ids: ids
        })
      } else {
        that.setData({
          showModal: false
        })
      }
    }, (err) => {
      console.log(err.errMsg)
    })
  },
  loadBanner: function () {
    // 未授权，用banner/wx
    const that = this;
    let url = app.globalData.URL + 'system/banner/wx/list';
    wx.request({
      url: url,
      method: 'GET',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        let imgUrls = res.data.rows
        that.setData({
          imgUrls: imgUrls,
          retu: false
        })
      }
    })
  },
  onShow: function () {
    this.loadBanner();
    // if (app.globalData.token) this.loadCoupon();
  },
  onLoad(options) {
    // 获取用户信息
    let that = this;
    // 扫码进入那机器码，用户扫码进入
    let jqm = decodeURIComponent(options.q);
    // if (app.globalData.jqm == '') {
    if (/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/.test(jqm)) {
      app.globalData.jqm = jqm
      that.setData({
        jqm: jqm
      })
    }
    // }

    // wx.getSetting({
    //   success: res => {
    //     if (res.authSetting['scope.userInfo']) {
    //       // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
    //       let url = app.globalData.URL + 'system/banner/list';
    //       let data = {
    //         imgUrls: []
    //       };
    //       app.wxRequest('GET', url, data, (res) => {
    //         if (res.code != 200) {
    //           wx.showModal({
    //             title: '登录过期，请重新登录',
    //             success() {
    //               wx.showLoading({
    //                 title: '登录中',
    //               })
    //               wx.login({
    //                 success: res => {
    //                   let code = res.code;
    //                   let url = app.globalData.URL + 'wx/openId/get/'
    //                   if (code) {
    //                     wx.request({
    //                       url: url + code,
    //                       method: 'POST',
    //                       // data:{
    //                       //   code:code
    //                       // },
    //                       header: {
    //                         'content-type': 'application/json' // 默认值
    //                       },
    //                       success: function (res) {
    //                         console.log(res)
    //                         let avatar = app.globalData.userInfo.avatarUrl;
    //                         let nickName = app.globalData.userInfo.nickName;
    //                         let sex = JSON.stringify(app.globalData.userInfo.gender);
    //                         let openId = res.data.openId;
    //                         let sessionKey = res.data.sessionKey;
    //                         let token = app.globalData.token;
    //                         console.log('1:' + avatar, '2' + nickName, '3' + sex, '4' + openId, '5' + sessionKey)
    //                         let url = app.globalData.URL + 'wx/login?openId=' + openId + '&sessionKey=' + sessionKey
    //                         wx.request({
    //                           method: 'POST',
    //                           url: url,
    //                           data: {
    //                             avatar: avatar,
    //                             nickName: nickName,
    //                             openId: openId,
    //                             sessionKey: sessionKey,
    //                             sex: sex
    //                           },
    //                           success: function (res) {
    //                             console.log(res)
    //                             getApp().globalData.token = res.data.data.token;
    //                             wx.setStorageSync('token', res.data.data.token);
    //                             if (wx.getStorageSync('token') == res.data.data.token) {
    //                               wx.hideLoading();
    //                               wx.showModal({
    //                                 title: '登陆成功',
    //                                 success() {
    //                                   that.loadCoupon();
    //                                 }
    //                               })
    //                             }
    //                           },
    //                         })
    //                       }
    //                     })
    //                   }
    //                 }
    //               })
    //             }
    //           })
    //         } else {
    //           that.loadCoupon();
    //         }
    //       }, (err) => {
    //         console.log(err.errMsg)
    //       })
    //     } else {


    //     }
    //   }
    // })
    // 实例化腾讯地图API核心类
    let qqmapsdk = new qqmap({
      key: 'SDKBZ-NUGLU-QN7VQ-4Q2RJ-3V6M7-HPBBQ' // 必填
    });
    //1、获取当前位置坐标
    // wx.getLocation({
    //   type: 'wgs84',
    //   success: function (res) {
    //     //2、根据坐标获取当前位置名称，显示在顶部:腾讯地图逆地址解析
    //     qqmapsdk.reverseGeocoder({
    //       location: {
    //         latitude: res.latitude,
    //         longitude: res.longitude
    //       },
    //       success: function (addressRes) {
    //         var address = addressRes.result.formatted_addresses.recommend;
    //         app.globalData.address = address;
    //         that.setData({
    //           city: addressRes.result.address_component.city
    //         })
    //       },
    //       fail(res) {
    //         console.log(res)
    //       }
    //     })
    //   }
    // })

  },
  //切换城市
  gocity() {
    wx.navigateTo({
      url: '/pages/switchcity/switchcity'
    })
  },
  // 领取优惠券
  getCoupon(e) {
    if (!this.redirectLogin()) return false;
    let that = this;
    let ids = e.currentTarget.dataset.id
    // 查询可领优惠券
    let url = app.globalData.URL + 'goods/coupon/user/receive';
    let data = { ids };
    app.wxRequest('GET', url, data, (res) => {
      console.log(res)
      if (res.code == 200) {
        wx.showModal({
          title: '领取成功',
          success() {
            that.setData({
              showModal: false
            })
          }
        })
      }
    }, (err) => {
      console.log(err.errMsg)
    })
  },
  // 领取所有优惠券
  allgetCoupon() {
    // 查询可领优惠券
    let that = this;
    let url = app.globalData.URL + 'goods/coupon/user/receive';
    let ids = that.data.ids;
    ids = ids.join(',');
    let data = {
      ids
    };
    app.wxRequest('GET', url, data, (res) => {
      console.log(res)
      if (res.code == 200) {
        wx.showModal({
          title: '领取成功',
          success() {
            that.setData({
              showModal: false
            })
          }
        })
      }
    }, (err) => {
      console.log(err.errMsg)
    })
  },
  // 关闭窗口
  closeYhj() {
    this.setData({
      showModal: false
    })
  }
})